import React, { useEffect, useState, useRef } from 'react'
import { useLocation } from 'react-router-dom'
import { SideBar } from 'antd-mobile';
import axios from 'axios'
import { Card } from '@nutui/nutui-react'
import { useThrottleFn } from 'ahooks';
import { Sticky } from '@nutui/nutui-react'
import { SubmitBar } from 'react-vant';
import { Button } from '@nutui/nutui-react'
import { Cart } from '@nutui/icons-react';
import { Popup } from 'antd-mobile'
import { Cell,Dialog } from '@nutui/nutui-react'
import { ProductCard } from 'react-vant';

export default function Xiang() {
  const [data, setData] = useState([])
  const [activeKey, setActiveKey] = useState('1');
  const [cart, setCart] = useState(() => JSON.parse(localStorage.getItem('cart')) || [])
  const [step, setStep] = useState({})
  const [animationClass, setAnimationClass] = useState('')
  const [visible5, setVisible5] = useState(false)
  const { run: handleScroll } = useThrottleFn(() => {
    let currentKey = items[0].key;
    for (const item of items) {
      const element = document.getElementById(`anchor-${item.key}`);
      if (!element)
        continue;
      const rect = element.getBoundingClientRect();
      if (rect.top <= 0) {
        currentKey = item.key;
      }
      else {
        break;
      }
    }
    setActiveKey(currentKey);
  }, {
    leading: true,
    trailing: true,
    wait: 100,
  });
  const mainElementRef = useRef(null);
  useEffect(() => {

    const mainElement = mainElementRef.current;
    if (!mainElement)
      return;
    mainElement.addEventListener('scroll', handleScroll);
    return () => {
      mainElement.removeEventListener('scroll', handleScroll);
    };

  }, []);
  const id = useLocation().state
  const [list, setList] = useState([])
  const getdian = async () => {
    const res = await axios.get(`http://localhost:3000/get_dian`, {
      params: { id: id }
    })
    setList(res.data)
    const parseData = JSON.parse(res.data[0].dishs)
    setData(parseData)
  }
  const addToCart = (item) => {
    setCart((prevCart) => {
      const existingItem = prevCart.find((cartItem) => cartItem.id === item.id)
      console.log(existingItem);
      if (existingItem) {
        return prevCart.map((cartItem) => cartItem.id === item.id ? { ...cartItem, num: cartItem.num + 1 } : cartItem)
      } else {
        return [...prevCart, { ...item, num: 1 }]
      }
    })
    console.log(cart);

    setAnimationClass('animate-ball')
    setTimeout(() => {
      setAnimationClass('')
    }, 1000)
  }
  const clearCar = () => {
    sessionStorage.removeItem('cart')
    setCart([])
  }
  const handleBallClick = (item) => {
    addToCart(item)
    setStep((prev) => ({
      ...prev,
      [item.id]: (prev[item.id] || 0) + 1
    }))
  }
  useEffect(() => {
    getdian()
  }, [])
  useEffect(() => {
    sessionStorage.setItem('cart', JSON.stringify(cart))
  }, [cart])
  const totalPrice = cart.reduce((acc, item) => acc + item.num * item.price, 0)
  const totalNum = cart.reduce((acc, item) => acc + item.num, 0)
  const items = [
    {
      key: '1', title: '焦香炸串', text: (<>
        {
          data.filter(item => item.type === '焦香炸串').map((item, index) => {
            return <Card key={index}
              src={item.img}
              title={item.name}
              price={item.price}
              num={item.num}
              extra={
                <>
                  <Button onClick={() => { handleBallClick(item) }} type="warning" shape='round'

                  >+</Button>
                  {step[item.id] > 0 && <span>{step[item.id]}</span>}
                  {step[item.id] > 0 && <div className={`ball ${animationClass}`}></div>}
                </>
              }
            >
            </Card>
          })
        }

      </>)
    },
    {
      key: '2', title: '肉丸肉串', text: (<>
        {
          data.filter(item => item.type === '肉丸肉串').map((item, index) => {
            return <Card key={index}
              src={item.img}
              title={item.name}
              price={item.price}
              num={item.num}
            >
            </Card>
          })
        }
      </>)
    },
    {
      key: '3', title: '菌菇豆制', text: (<>
        {
          data.filter(item => item.type === '菌菇豆制').map((item, index) => {
            return <Card key={index}
              src={item.img}
              title={item.name}
              price={item.price}
              num={item.num}
            >
            </Card>
          })
        }
      </>)
    },
    {
      key: '4', title: '配粉配饭', text: (<>
        {
          data.filter(item => item.type === '配粉配饭').map((item, index) => {
            return <Card key={index}
              src={item.img}
              title={item.name}
              price={item.price}
              num={item.num}
            >
            </Card>
          })
        }
      </>)
    },
  ];


  return (
    <div style={{ height: '700px' }}>
      <div>
        {
          list.map(item => {
            return (<div key={item._id}>
              <div style={{ width: '400px', height: '100px', backgroundColor: 'pink', textAlign: 'center', lineHeight: '100px' }}>
                <h2>{item.name}</h2>
              </div>
              <div className='container2'>
                <div className='side'>
                  <SideBar activeKey={activeKey} onChange={key => {
                    var _a;
                    (_a = document.getElementById(`anchor-${key}`)) === null || _a === void 0 ? void 0 : _a.scrollIntoView();
                  }}>
                    {items.map(item => (<SideBar.Item key={item.key} title={item.title} />))}
                  </SideBar>
                </div>
                <div className='main' ref={mainElementRef}>
                  {items.map(item => (<div key={item.key}>
                    <h2 id={`anchor-${item.key}`}>{item.title}</h2>
                    {item.text}
                  </div>))}
                </div>
              </div>
            </div>)
          })
        }
      </div>
      <Sticky threshold={0} position="bottom">

        <div className="demo-submit-bar" style={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          height: '50px',
          width: '400px',
          textAlign: 'center',
          lineHeight: '180px',
          zIndex: 1000
        }}><SubmitBar disabled={cart.length === 0} price={totalPrice*100} buttonText="去结算" ><Cart onClick={() => {
          setVisible5(true)
        }} width='20px' height={'20px'} />
        <span style={{color:'red', marginLeft:'3px',marginTop:'-20px'}}>{totalNum}</span>
        </SubmitBar></div>
        <Popup
          visible={visible5}
          onMaskClick={() => {
            setVisible5(false)
          }}
          bodyStyle={{
            borderTopLeftRadius: '8px',
            borderTopRightRadius: '8px',
            minHeight: '40vh',
          }}
        >
          {
            cart.map((item, index) => {
              return <div className="demo-popup" key={index}>
                <ProductCard
                  num={item.num}
                  price={item.price}
                  title={item.name}
                  thumb={item.img}
                />
              </div>
            })
          }
          <Cell style={{ position: 'absolute', bottom: '0', left: '0', width: '100%', height: '50px', textAlign: 'center', lineHeight: '50px' }}
            title="清空购物车"
            onClick={() => {
              Dialog.alert({
                className: 'dialog-func',
                title: '是否清除购物车',
                onConfirm:()=>{
                  clearCar()
                }
              })
            }}
          />
        </Popup>
      </Sticky>
    </div >

  )
}
